package com.bluetrum.abmate;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bluetrum.abmate.cmd.SimpleRequestCallback2;
import com.bluetrum.abmate.databinding.ActivityMainBinding;
import com.bluetrum.abmate.databinding.CollapsingToolbarActiveDeviceBinding;
import com.bluetrum.abmate.databinding.LayoutDevicePresentationBinding;
import com.bluetrum.abmate.databinding.LayoutInfoNoManagedDeviceBinding;
import com.bluetrum.abmate.dialog.BottomSheetQuickPairDialogFragment;
import com.bluetrum.abmate.dialog.BottomSheetScannerDialogFragment;
import com.bluetrum.abmate.models.ABEarbuds;
import com.bluetrum.abmate.utils.Utils;
import com.bluetrum.abmate.viewmodels.DeviceRepository;
import com.bluetrum.abmate.viewmodels.ScannerViewModel;
import com.bluetrum.devicemanager.cmd.Request;
import com.bluetrum.devicemanager.cmd.request.ClearPairRecordRequest;
import com.bluetrum.devicemanager.models.DeviceComponentPower;
import com.bluetrum.devicemanager.models.DevicePower;
import com.bluetrum.devicemanager.models.ABDevice;
import com.google.android.material.navigation.NavigationBarView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.splashscreen.SplashScreen;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.PreferenceManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;
import pub.devrel.easypermissions.EasyPermissions;
import timber.log.Timber;

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity
        implements NavigationBarView.OnItemSelectedListener,
        BottomSheetScannerDialogFragment.BottomSheetScannerListener {

    private static final String CURRENT_FRAGMENT = "CURRENT_FRAGMENT";
    private static final String SCANNER_FRAGMENT = "SCANNER_FRAGMENT";
    private static final String QUICK_PAIR_FRAGMENT = "QUICK_PAIR_FRAGMENT";

    private static final int PERMISSIONS_REQUEST_CODE = 999;

    private ScannerViewModel mViewModel;

    // ViewBinding
    private ActivityMainBinding binding;
    private CollapsingToolbarActiveDeviceBinding layoutActiveDeviceBinding;
    private LayoutDevicePresentationBinding layoutDevicePresentationBinding;
    private LayoutInfoNoManagedDeviceBinding layoutInfoNoManagedDevice;

    private String appName;
    private String titleNoActiveDevice;

    private int mediumAnimationDuration;

    private HomeFragment mHomeFragment;
    private FunctionFragment mFunctionFragment;
    private SettingsFragment mSettingsFragment;

    private BottomSheetQuickPairDialogFragment quickPairDialogFragment;


    // sco链路
    private BluetoothAdapter bluetoothAdapter;
    private AudioManager audioManager;
    private AudioRecord audioRecord;
    private AudioTrack audioTrack;
    private boolean isRecording = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SplashScreen.installSplashScreen(this);
        super.onCreate(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(ScannerViewModel.class);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        layoutActiveDeviceBinding = binding.collapsingToolbarActiveDevice;
        layoutDevicePresentationBinding = layoutActiveDeviceBinding.layoutDevicePresentation;
        layoutInfoNoManagedDevice = layoutActiveDeviceBinding.layoutInfoNoManagedDevice;

        // Load Resources
        appName = getResources().getString(R.string.app_name);
        titleNoActiveDevice = getResources().getString(R.string.no_active_device_title);
        mediumAnimationDuration = getResources().getInteger(android.R.integer.config_mediumAnimTime);

        // 设置标题
        binding.collapsingToolbarLayout.setTitle(appName);

        mHomeFragment = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_home);
        mFunctionFragment = (FunctionFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_function);
        mSettingsFragment = (SettingsFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_settings);

        binding.bottomNavigationView.setOnItemSelectedListener(this);
        // todo 添加设备
        layoutInfoNoManagedDevice.addDeviceButton.setOnClickListener(this::launchScanner);
        // todo 断开，此时只断开了ble，bt音频蓝牙未断开
        binding.disconnectButton.setOnClickListener(v -> disconnectDevice());

        if (savedInstanceState == null) {
            onNavigationItemSelected(binding.bottomNavigationView.getMenu().findItem(R.id.navigation_home));
        } else {
            binding.bottomNavigationView.setSelectedItemId(savedInstanceState.getInt(CURRENT_FRAGMENT));
        }

        // 设备连接状态
        mViewModel.getDeviceConnectionState().observe(this, this::onDeviceConnectionStateChanged);
        // 当前弹窗设备
        mViewModel.getPopupDevice().observe(this, this::onPopupDeviceChanged);
        // 当前已连接设备
        mViewModel.getActiveDevice().observe(this, this::onActiveDeviceChanged);
        // 电量回报
        mViewModel.getDevicePower().observe(this, this::onReceiveDevicePower);
        // 设置标题
        mViewModel.getDeviceName().observe(this, deviceName -> binding.collapsingToolbarLayout.setTitle(deviceName));

        // 这里不能使用匿名类，不然会被GC回收
        PreferenceManager.getDefaultSharedPreferences(this)
                .registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);

        updateQuickConnectState();

        mViewModel.getDeviceRepository().getScanningState().observe(this, this::onScanningStateChanged);

        // TODO: 这里是方便测试，以后会规范代码和流程
        final String[] rationale = {getString(R.string.permission_rationale_read_external_storage)};
        List<String> permissions = new ArrayList<String>(
                Arrays.asList(
                        Manifest.permission.READ_EXTERNAL_STORAGE
                )
        ) {{
            if (Utils.isAndroid12OrAbove()) {
                add(Manifest.permission.BLUETOOTH_SCAN);
                add(Manifest.permission.BLUETOOTH_CONNECT);
                rationale[0] += "\n";
                rationale[0] += getString(R.string.permission_rationale_bluetooth);
            } else {
                add(Manifest.permission.ACCESS_FINE_LOCATION);
                add(Manifest.permission.ACCESS_COARSE_LOCATION);
                rationale[0] += "\n";
                rationale[0] += getString(R.string.permission_rationale_location);
            }
        }};
        // 获取权限
        EasyPermissions.requestPermissions(this,
                rationale[0],
                PERMISSIONS_REQUEST_CODE,
                permissions.toArray(new String[0])
        );

        // sco链路
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(CURRENT_FRAGMENT, binding.bottomNavigationView.getSelectedItemId());
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (id == R.id.navigation_home) {
            ft.show(mHomeFragment).hide(mFunctionFragment).hide(mSettingsFragment);
        } else if (id == R.id.navigation_function) {
            ft.hide(mHomeFragment).show(mFunctionFragment).hide(mSettingsFragment);
        } else if (id == R.id.navigation_settings) {
            ft.hide(mHomeFragment).hide(mFunctionFragment).show(mSettingsFragment);
        }
        ft.commit();
        return true;
    }

    // 不能使用匿名类，不然会被GC回收
    private final SharedPreferences.OnSharedPreferenceChangeListener
            onSharedPreferenceChangeListener = (sharedPreferences, key) -> {
        if (Utils.PREFS_ENABLE_QUICK_CONNECT.equals(key)) {
            updateQuickConnectState();
        }
    };

    /**
     * 快速连接，自动开启扫描连接
     */
    private void updateQuickConnectState() {
        boolean enabled = Utils.getPrefsEnableQuickConnect(this);
        if (enabled) {
            ABDevice device = mViewModel.getActiveDevice().getValue();
            if (device == null) {
                mViewModel.getDeviceRepository().startScan();
            }

            layoutInfoNoManagedDevice.addDeviceButton.setVisibility(View.GONE);
            binding.disconnectButton.setVisibility(View.GONE);
        } else {
            mViewModel.getDeviceRepository().stopScan();
            layoutInfoNoManagedDevice.addDeviceButton.setVisibility(View.VISIBLE);

            ABDevice device = mViewModel.getActiveDevice().getValue();
            if (device != null) {
                binding.disconnectButton.setVisibility(View.VISIBLE);
            }
        }
    }

    private void onScanningStateChanged(Boolean scanning) {
        if (scanning != null) {
            binding.progressBar.setVisibility(scanning ? View.VISIBLE : View.GONE);
        }
    }

    private void onDeviceConnectionStateChanged(Integer state) {
        if (state != null) {
            Timber.tag("===监控蓝牙状态state").e("====状态:%s", state);
            Timber.d("onDeviceConnectionStateChanged: %s", DeviceRepository.getConnectionStateName(state));

            if (state == DeviceRepository.DEVICE_CONNECTION_STATE_IDLE) {
                // Hide disconnect button
                binding.disconnectButton.setVisibility(View.GONE);
                // Hide device information
                layoutInfoNoManagedDevice.connectionStateTextView.setText(null);
                layoutDevicePresentationBinding.deviceInformationView.setVisibility(View.GONE);
                // Show info 'No Device'
                layoutInfoNoManagedDevice.progressIndicatorLayout.setVisibility(View.GONE);
                layoutInfoNoManagedDevice.emptyView.setVisibility(View.VISIBLE);
                layoutInfoNoManagedDevice.addDeviceButton.setEnabled(true);
                layoutInfoNoManagedDevice.getRoot().setVisibility(View.VISIBLE);
                // Set title 'No Device'
                binding.collapsingToolbarLayout.setTitle(titleNoActiveDevice);
                // Expand AppBarLayout
                binding.appBarLayout.setExpanded(true, true);
            } else if (state == DeviceRepository.DEVICE_CONNECTION_STATE_PAIRING) {
                layoutInfoNoManagedDevice.emptyView.setVisibility(View.INVISIBLE);
                layoutInfoNoManagedDevice.connectionStateTextView.setText(R.string.pairing);
                layoutInfoNoManagedDevice.progressIndicator.setVisibility(View.VISIBLE);
                layoutInfoNoManagedDevice.progressIndicatorLayout.setVisibility(View.VISIBLE);
            } else if (state == DeviceRepository.DEVICE_CONNECTION_STATE_PAIRED) {
                layoutInfoNoManagedDevice.connectionStateTextView.setText(R.string.paired);
            } else if (state == DeviceRepository.DEVICE_CONNECTION_STATE_CONNECTING) {
                layoutInfoNoManagedDevice.connectionStateTextView.setText(R.string.connecting);
            } else if (state == DeviceRepository.DEVICE_CONNECTION_STATE_CONNECTED) {
                layoutInfoNoManagedDevice.connectionStateTextView.setText(R.string.connected);
            } else if (state == DeviceRepository.DEVICE_CONNECTION_STATE_AUTHENTICATING) {
                layoutInfoNoManagedDevice.connectionStateTextView.setText(R.string.authenticating);
            } else if (state == DeviceRepository.DEVICE_CONNECTION_STATE_AUTHENTICATED) {
                layoutInfoNoManagedDevice.connectionStateTextView.setText(R.string.authenticated);
                layoutInfoNoManagedDevice.progressIndicatorLayout.setVisibility(View.GONE);
                // Hide no device
                layoutInfoNoManagedDevice.getRoot().setVisibility(View.INVISIBLE);
                // Fade in
                layoutDevicePresentationBinding.deviceInformationView.setAlpha(0);
                layoutDevicePresentationBinding.deviceInformationView.setVisibility(View.VISIBLE);
                layoutDevicePresentationBinding.deviceInformationView.animate().alpha(1.0f).setDuration(mediumAnimationDuration);
                // Show disconnect button
                // FIXME: Hide disconnect button in Quick Connect mode?
                if (!Utils.getPrefsEnableQuickConnect(this)) {
                    binding.disconnectButton.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void onPopupDeviceChanged(ABDevice device) {
        Timber.d("onPopupDeviceChanged: %s", device);
        if (device != null) {
            if (quickPairDialogFragment == null) {
                // 弹窗
                quickPairDialogFragment = new BottomSheetQuickPairDialogFragment(device);
                quickPairDialogFragment.show(getSupportFragmentManager(), QUICK_PAIR_FRAGMENT);
            }
        } else {
            // 取消弹窗
            if (quickPairDialogFragment != null) {
                quickPairDialogFragment.dismiss();
                quickPairDialogFragment = null;
            }
        }
    }

    private void onActiveDeviceChanged(ABDevice device) {
        Timber.w("onActiveDeviceChanged: %s", device);
        Timber.e("===onActiveDeviceChanged: %s", device);
        if (device != null) {
            binding.progressBar.setVisibility(View.GONE);
            // Show device info
            showActiveDeviceInfo(device);
            // Expand AppBarLayout
            binding.appBarLayout.setExpanded(true, true);
        }
    }

    /**
     * 显示当前连接的设备信息
     * @param device 蓝牙设备 {@link ABDevice}
     */
    private void showActiveDeviceInfo(@NonNull final ABDevice device) {
        if (device instanceof ABEarbuds) {
            showActiveDeviceInfo((ABEarbuds) device);

            // todo 开启连接设备的soc链路
            connectToSco((ABEarbuds) device);
        }
    }

    /**
     * 显示当前连接的耳机信息
     * @param earBuds 蓝牙耳机设备 {@link ABEarbuds}
     */
    private void showActiveDeviceInfo(@NonNull final ABEarbuds earBuds) {
        // Set title, device name
        binding.collapsingToolbarLayout.setTitle(earBuds.getName());

        // NOTE: 只有版本1才有电量值，其他通过命令获取
        if (earBuds.getFeatureVersion() != 1) {
            return;
        }

        // 左耳
        // 文字
        int leftBatteryLevel = earBuds.getLeftBatteryLevel();
        setBatteryLevelText(layoutDevicePresentationBinding.leftBatteryTextView, leftBatteryLevel);
        // 图像
        boolean isLeftPodCharging = earBuds.isLeftChanging();
        if (isLeftPodCharging) {
            layoutDevicePresentationBinding.leftBatteryImageView.setImageResource(R.mipmap.battery_charging);
        } else {
            setBatteryLevelImage(layoutDevicePresentationBinding.leftBatteryImageView, leftBatteryLevel);
        }
        layoutDevicePresentationBinding.leftBatteryLayout.setVisibility(View.VISIBLE);

        // 右耳
        // 文字
        int rightBatteryLevel = earBuds.getRightBatteryLevel();
        setBatteryLevelText(layoutDevicePresentationBinding.rightBatteryTextView, rightBatteryLevel);
        // 图像
        boolean isRightPodCharging = earBuds.isRightChanging();
        if (isRightPodCharging) {
            layoutDevicePresentationBinding.rightBatteryImageView.setImageResource(R.mipmap.battery_charging);
        } else {
            setBatteryLevelImage(layoutDevicePresentationBinding.rightBatteryImageView, rightBatteryLevel);
        }
        layoutDevicePresentationBinding.rightBatteryLayout.setVisibility(View.VISIBLE);

        // 充电盒
        // 文字
        int caseBatteryLevel = earBuds.getCaseBatteryLevel();
        setBatteryLevelText(layoutDevicePresentationBinding.caseBatteryTextView, caseBatteryLevel);
        // 图像
        boolean isCaseCharging = earBuds.isCaseCharging();
        if (isCaseCharging) {
            layoutDevicePresentationBinding.caseBatteryImageView.setImageResource(R.mipmap.battery_charging);
        } else {
            setBatteryLevelImage(layoutDevicePresentationBinding.caseBatteryImageView, caseBatteryLevel);
        }
        layoutDevicePresentationBinding.caseBatteryLayout.setVisibility(View.VISIBLE);
    }

    private void setBatteryLevelText(@NonNull TextView textView, int batteryLevel) {
        String batteryLevelText = String.format("%s%%", batteryLevel);
        textView.setText(batteryLevelText);
    }

    private void setBatteryLevelImage(@NonNull ImageView imageView, int batteryLevel) {
        if (batteryLevel >= 95) {
            imageView.setImageResource(R.mipmap.battery_100);
        } else if (batteryLevel >= 80) {
            imageView.setImageResource(R.mipmap.battery_80);
        } else if (batteryLevel >= 60) {
            imageView.setImageResource(R.mipmap.battery_60);
        } else if (batteryLevel >= 40) {
            imageView.setImageResource(R.mipmap.battery_40);
        } else if (batteryLevel >= 20) {
            imageView.setImageResource(R.mipmap.battery_20);
        } else if (batteryLevel >= 0) {
            imageView.setImageResource(R.mipmap.battery_0);
        }
    }

    private void onReceiveDevicePower(@Nullable DevicePower power) {
//        Timber.v("%s", power);
        if (power != null) {
            // 左耳
            DeviceComponentPower leftSidePower = power.getLeftSidePower();
            if (leftSidePower != null) {
                // 文字
                int leftPowerLevel = leftSidePower.getPowerLevel();
                setBatteryLevelText(layoutDevicePresentationBinding.leftBatteryTextView, leftPowerLevel);
                // 图像
                boolean isLeftSideCharging = leftSidePower.isCharging();
                if (isLeftSideCharging) {
                    layoutDevicePresentationBinding.leftBatteryImageView.setImageResource(R.mipmap.battery_charging);
                } else {
                    setBatteryLevelImage(layoutDevicePresentationBinding.leftBatteryImageView, leftPowerLevel);
                }
                layoutDevicePresentationBinding.leftBatteryLayout.setVisibility(View.VISIBLE);
            } else {
                layoutDevicePresentationBinding.leftBatteryTextView.setText("?");
                layoutDevicePresentationBinding.leftBatteryImageView.setImageBitmap(null);
            }

            // 右耳
            DeviceComponentPower rightSidePower = power.getRightSidePower();
            if (rightSidePower != null) {
                // 文字
                int rightPowerLevel = rightSidePower.getPowerLevel();
                setBatteryLevelText(layoutDevicePresentationBinding.rightBatteryTextView, rightPowerLevel);
                // 图像
                boolean isRightSideCharging = rightSidePower.isCharging();
                if (isRightSideCharging) {
                    layoutDevicePresentationBinding.rightBatteryImageView.setImageResource(R.mipmap.battery_charging);
                } else {
                    setBatteryLevelImage(layoutDevicePresentationBinding.rightBatteryImageView, rightPowerLevel);
                }
                layoutDevicePresentationBinding.rightBatteryLayout.setVisibility(View.VISIBLE);
            } else {
                layoutDevicePresentationBinding.rightBatteryTextView.setText("?");
                layoutDevicePresentationBinding.rightBatteryImageView.setImageBitmap(null);
            }

            // 充电盒
            DeviceComponentPower casePower = power.getCasePower();
            if (casePower != null) {
                // 文字
                int casePowerLevel = casePower.getPowerLevel();
                setBatteryLevelText(layoutDevicePresentationBinding.caseBatteryTextView, casePowerLevel);
                // 图像
                boolean isCaseCharging = casePower.isCharging();
                if (isCaseCharging) {
                    layoutDevicePresentationBinding.caseBatteryImageView.setImageResource(R.mipmap.battery_charging);
                } else {
                    setBatteryLevelImage(layoutDevicePresentationBinding.caseBatteryImageView, casePowerLevel);
                }
                layoutDevicePresentationBinding.caseBatteryLayout.setVisibility(View.VISIBLE);
            } else {
                layoutDevicePresentationBinding.caseBatteryTextView.setText("?");
                layoutDevicePresentationBinding.caseBatteryImageView.setImageBitmap(null);
            }
        }
    }

    private void launchScanner(View v) {
        BottomSheetScannerDialogFragment dialogFragment = BottomSheetScannerDialogFragment.getInstance();
        dialogFragment.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onCreate(owner);
                layoutInfoNoManagedDevice.addDeviceButton.setEnabled(false);
            }

            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                DefaultLifecycleObserver.super.onDestroy(owner);
                if (mViewModel.getPreparingDevice().getValue() == null) {
                    layoutInfoNoManagedDevice.addDeviceButton.setEnabled(true);
                }
            }
        });
        dialogFragment.show(getSupportFragmentManager(), SCANNER_FRAGMENT);
    }

    private void disconnectDevice() {
//        mViewModel.getDeviceRepository().disconnect();

        // TODO 清除配对记录时，可以忽略设备上的蓝牙
        Request request = new ClearPairRecordRequest();
        sendRequestAndWaitSuccess(request, null);
        stopSco();
    }

    // 扫描的
    @Override
    public void selectedDevice(ABDevice device) {
        Timber.d("device = %s", device.getBleName());
        mViewModel.getDeviceRepository().bondDevice(device);
    }

    /* Permissions */

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Timber.e("===onResume=device = %s", "是否存在当前活动的设备");
        Timber.e("===onResume=getActiveDevice = %s", mViewModel.getActiveDevice().getValue());
        if (mViewModel.getActiveDevice().getValue() != null){
            tryToConnect(mViewModel.getActiveDevice().getValue());
        }
    }

    /**
     * 尝试回连
     */
    public void tryToConnect(ABDevice device) {
        Timber.e("===回连=device = %s", device.getBleName());
        mViewModel.getDeviceRepository().bondDevice(device);
    }

    /*
   统一处理返回值Boolean的Request，并提示可能的失败和超时
    */
    private void sendRequestAndWaitSuccess(@NonNull final Request request, @Nullable SimpleRequestCallback2 callback2) {

        mViewModel.sendRequest(request, new SimpleRequestCallback2() {
            @Override
            public void onComplete(boolean result) {
                Timber.d("sendRequest result = %s", result);

                if (result) {
                    Utils.showToast(MainActivity.this, R.string.request_succeeded);
                } else {
                    Utils.showToast(MainActivity.this, R.string.request_failed);
                }

                if (callback2 != null) {
                    callback2.onComplete(result);
                }
            }

            @Override
            public void onTimeout() {
                Timber.w("Request timeout");
                Utils.showToast(MainActivity.this, R.string.request_timeout);

                if (callback2 != null) {
                    callback2.onTimeout();
                }
            }
        });
    }


    // sco链路
    private void connectToSco(@NonNull final ABEarbuds earBuds) {
        Timber.e("===sco链路=ABEarbuds = %s", earBuds.getBleAddress()+","+earBuds.getAddress()+","+earBuds.getBtAddress());

        // 例如，使用 BluetoothDevice 的地址连接耳机
//        BluetoothDevice device = bluetoothAdapter.getRemoteDevice("00:11:22:33:44:55"); // 替换为耳机的 MAC 地址
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(earBuds.getBleAddress());
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        device.createBond(); // 创建配对
        Timber.e("===sco链路=创建配对 = %s", "创建配对");

        startSco();
        startRecording();
    }

    private void startRecording() {
        Timber.e("===sco链路=开启录音 = %s", "startRecording");
        /*int sampleRate = 8000; // 采样率
        int channelConfig = AudioFormat.CHANNEL_IN_MONO;
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
//        int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
        int bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            //Timber.e("===sco链路=录音权限 = %s", "未打开录音权限");
            return;
        }
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
        audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, sampleRate, channelConfig, audioFormat, bufferSize, AudioTrack.MODE_STREAM);*/


        int sampleRate = 8000;  // 采样率
        int bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            //Timber.e("===sco链路=录音权限 = %s", "未打开录音权限");
            return;
        }
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);

        int outputBufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, outputBufferSize, AudioTrack.MODE_STREAM);

        audioRecord.startRecording();
        audioTrack.play();
        isRecording = true;
        Timber.e("===sco链路=开启录音 = %s", "开启录音");

        new Thread(() -> {
            byte[] audioBuffer = new byte[bufferSize];
            while (isRecording) {
                int bytesRead = audioRecord.read(audioBuffer, 0, bufferSize);
                if (bytesRead > 0) {
                    // 处理音频数据，例如发送到服务器进行翻译或处理
                    Timber.e("===sco链路=处理音频数据 = %s", bytesRead);
                    audioTrack.write(audioBuffer, 0, bytesRead);
                }
            }
        }).start();

    }

    private void startSco(){
        // 启用 SCO 链路
        if (audioManager != null) {
            audioManager.startBluetoothSco();
            audioManager.setBluetoothScoOn(true);
        }
    }

    private void stopSco(){
        // 停止 SCO 链路
        if (audioManager != null) {
            audioManager.stopBluetoothSco();
            audioManager.setBluetoothScoOn(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRecording = false;
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
        }
        if (audioTrack != null) {
            audioTrack.stop();
            audioTrack.release();
        }
        stopSco();
    }

}